import pandas as pd
import numpy as np
import glob
import wave
import pydub
import os
def is_a_num(string):
    try:
        float(string)  # return float(string)
    except:
        return string  # return ''
def selectChn(file_path):
    result = {}
    temp = ["ChnName", "ChnData", "FrameRate"]
    for para in temp:
                result[para] = []
    ret = []
    plugin_pys = [x[-4:] for x in glob.glob(file_path)]
    if len(plugin_pys) == 0:
        plugin_pys = [x[-4:] for x in glob.glob('.'+file_path)]
    else:
        pass
    # print(plugin_pys)

    for k in plugin_pys:

        if k == '.csv':
            frameRate = 100
            li = [False, False, False, False, False, False, False, False, False, False, 
                    False, False, False, False, False, False, False, False]
            df = pd.read_csv(file_path, header = None, index_col = None, low_memory=False)
            # df.dropna()
            # df.drop(df.columns[[0,1,2,3]], axis=1,inplace=True)
            y = []
            # print("s", df.shape[1])
            for i in range(df.shape[1]):
                # df = df.values.tolist() 
                for j in range(1,df.shape[0]):
                    if not(is_a_num(df.iloc[j][i])) and (df.iloc[j][i] != ''):
                        # if df.iloc[j][i] == '':
                        li[i] = True
                '''if (li[i] == True):
                    print(df.iloc[0][i])'''
            for x in range(df.shape[1]):
                if df.iloc[5:10, x].isnull().all():
                    y.append(x)
                    # df.drop(df.columns[[x]], axis=1, inplace=True)
            # print(y)
            for x in y:
                # print(x)
                li[x] = False
            for i in range(df.shape[1]):
                # df = df.values.tolist() 
                if (li[i] == True):
                    # print(df.iloc[0][i])
                    result[temp[0]].append(df.iloc[0][i])
                    result[temp[1]].append(df.iloc[:, i])
                    ret.append(df.iloc[:, i])
            result[temp[2]].append(frameRate)

        if k == '.wav':
            file = wave.open(file_path, "rb")
            params = file.getparams()
            nframes = params[3]
            frameRate = params[2]
            str_data = file.readframes(nframes)
            nchannels = params[0]
            strData = str_data
            wave_data = np.frombuffer(strData, dtype=np.short)
            wave_data = np.reshape(wave_data, [nframes, nchannels])
            file.close()
            # li = [True, True]
            for i in range(wave_data.shape[1]):
                if i == 0:
                    result[temp[0]].append("rightChn")
                    # print("rightChn")
                if i == 1:
                    result[temp[0]].append("leftChn")
                    # print("leftChn")
                result[temp[1]].append(wave_data[:, i])
                ret.append(wave_data[:, i]) 
            result[temp[2]].append(frameRate)
            
        if k == '.mp3':
            a = pydub.AudioSegment.from_mp3(file_path)
            # framerate = a.frame_rate    # framerate采样频率 = 48000
            nframes = int(a.frame_count())    # 采样点数 = 617400
            frameRate = a.frame_rate    # framerate采样频率 = 48000
            y = np.array(a.get_array_of_samples())
            y = y.reshape((-1, 2))
            for i in range(y.shape[1]):
                if i == 0:
                    result[temp[0]].append("rightChn")
                    # print("rightChn")
                if i == 1:
                    result[temp[0]].append("rightChn")
                    # print("leftChn")
                result[temp[1]].append(y[:, i])
                ret.append(y[:, i])
            result[temp[2]].append(frameRate)

        if k == '.npy':
            # data = np.load('./hm3/test.npy')
            frameRate = 80
            data = np.load(file_path, encoding = "latin1", allow_pickle=True)
            li = [False, False, False, False, False, False, False, False, False, False, 
                    False, False, False, False, False, False, False, False]
            for i in range(data.shape[1]):
                li[i] = True
                if (li[i] ==True):
                    result[temp[0]].append("Chn"+str(round(data[0][i], 2)))
                    # print(data[0][i])
                result[temp[1]].append(data[:, i])
                ret.append(data[:, i])
            result[temp[2]].append(frameRate)

        if k == '.dat':
            frameRate = 60
            with open(file = file_path, mode = 'rb') as f:
                data = f.read()
            block_num = int(os.path.getsize(file_path)/512/8)
            # print(block_num) == 446
            lead_name = ['I', 'II', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6']
            output = {}
            for name in lead_name:
                output[name] = []
            li = [False, False, False, False, False, False, False, False, False, False, 
                False, False, False, False, False, False, False, False]
            index = 0    # 
            for k in range(block_num):   # 读取数据块数，这里读取block_num块
                for i in range(8):   # 导联数
                    for j in range(256):  #每一导联的数据点数
                        byte_low = bin(data[index])   #这里读取两个字节
                        byte_high = bin(data[index+1])
                        index += 2    #每读取两个字节，对data的索引加2
                        data_plot = str(byte_high[3:] + byte_low[2:])   #两个字节以二进制拼接，并且要祛除符号位
                        if byte_high[2] == '0':   # 符号位为正，直接按照原码读取
                            value = int(data_plot, 2) * 0.0122    #二进制转化为十进制，并且按照规则将单位转化为mv
                        elif byte_high[2] == '1':  #符号位为负，按照补码的规则转化为原码
                            negative = ''    
                            for m in range(len(data_plot)):  #对除符号位以外的取反
                                if data_plot[m] == '0':
                                    negative += '1'
                                elif data_plot[m] == '1':
                                    negative += '0'
                                else:
                                    print("data_plot is not 0 or 1!")
                            value = -1 * (int(negative, 2)+1) * 0.0122    
                        else:
                            print("data符号出错!")
                            # print(value)
                        output[lead_name[i]].append(value)

            for i in range(len(lead_name)):
                li[i] = True
                if (li[i] ==True):
                    result[temp[0]].append(lead_name[i])
                    # print(lead_name[i])
                ret.append(output[lead_name[i]])
                result[temp[1]].append(output[lead_name[i]])
            result[temp[2]].append(frameRate)
    return result
    
def newChn(file_path, param):
    newData = []
    plugin_pys = [x[-4:] for x in glob.glob(file_path)]
    if len(plugin_pys) == 0:
        plugin_pys = [x[-4:] for x in glob.glob('.'+file_path)]
    else:
        pass
    for k in plugin_pys:
        if k == '.csv':
            # frameRate = 100
            df = pd.read_csv(file_path, header = None, index_col = None, low_memory=False)    
            for i in range(len(param)):
                for j in range(df.shape[1]):
                    if param[i] == df.iloc[0][j]:
                        newData.append(df.iloc[:, j])

        if k == '.wav':
            file = wave.open(file_path, "rb")
            params = file.getparams()
            nframes = params[3]
            # frameRate = params[2]
            str_data = file.readframes(nframes)
            nchannels = params[0]
            strData = str_data
            wave_data = np.frombuffer(strData, dtype=np.short)
            wave_data = np.reshape(wave_data, [nframes, nchannels])
            file.close()
            for i in range(len(param)):
                if param[i] == "rightChn":
                    newData.append(wave_data[:, i])
                if param[i] == "leftChn":
                    newData.append(wave_data[:, i])

        if k == '.mp3':
            a = pydub.AudioSegment.from_mp3(file_path)
            # framerate = a.frame_rate    # framerate采样频率 = 48000
            nframes = int(a.frame_count())    # 采样点数 = 617400
            # frameRate = a.frame_rate    # framerate采样频率 = 48000
            y = np.array(a.get_array_of_samples())
            y = y.reshape((-1, 2))
            for i in range(len(param)):
                if param[i] == "rightChn":
                    newData.append(y[:, i])
                if param[i] == "leftChn":
                    newData.append(y[:, i])

        if k == '.npy':
            # frameRate = 80
            data = np.load(file_path, encoding = "latin1", allow_pickle=True)
            for i in range(len(param)):
                for j in range(data.shape[1]):
                    if param[i] == "Chn"+str(round(data[0][j], 2)):
                        newData.append(data[:, j])
        if k == '.dat':
            # frameRate = 60
            with open(file = file_path, mode = 'rb') as f:
                data = f.read()
            block_num = int(os.path.getsize(file_path)/512/8)
            # print(block_num) == 446
            lead_name = ['I', 'II', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6']
            output = {}
            for name in lead_name:
                output[name] = []
            li = [False, False, False, False, False, False, False, False, False, False, 
                False, False, False, False, False, False, False, False]
            index = 0    # 
            for k in range(block_num):   # 读取数据块数，这里读取block_num块
                for i in range(8):   # 导联数
                    for j in range(256):  #每一导联的数据点数
                        byte_low = bin(data[index])   #这里读取两个字节
                        byte_high = bin(data[index+1])
                        index += 2    #每读取两个字节，对data的索引加2
                        data_plot = str(byte_high[3:] + byte_low[2:])   #两个字节以二进制拼接，并且要祛除符号位
                        if byte_high[2] == '0':   # 符号位为正，直接按照原码读取
                            value = int(data_plot, 2) * 0.0122    #二进制转化为十进制，并且按照规则将单位转化为mv
                        elif byte_high[2] == '1':  #符号位为负，按照补码的规则转化为原码
                            negative = ''    
                            for m in range(len(data_plot)):  #对除符号位以外的取反
                                if data_plot[m] == '0':
                                    negative += '1'
                                elif data_plot[m] == '1':
                                    negative += '0'
                                else:
                                    print("data_plot is not 0 or 1!")
                            value = -1 * (int(negative, 2)+1) * 0.0122    
                        else:
                            print("data符号出错!")
                            # print(value)
                        output[lead_name[i]].append(value)

            for i in range(len(param)):
                for j in range(len(lead_name)):
                    if param[i] == lead_name[j]:
                        newData.append(output[lead_name[j]])  
    return newData

if __name__ == '__main__':
    '''
    x = selectChn('./csv_fund_quotes/q_217022_债券型-混合债_招商产业债券A.csv').get("ChnName")    # commented
    y = selectChn('./csv_fund_quotes/q_217022_债券型-混合债_招商产业债券A.csv').get("ChnData")    # commented
    z = selectChn('./csv_fund_quotes/q_217022_债券型-混合债_招商产业债券A.csv').get("FrameRate")    # commented
    z = int("".join([str(i)for i in z]))   # change list into int
    print(x,"\n",y,"\n", z)
    '''
    newChn('./hm3/wokan14s.mp3', ['leftChn', 'rightChn'])
